package com.googlecode.chigs.web.config.configuration;

import java.io.File;
import java.util.List;

import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.authorization.strategies.role.annotations.AuthorizeInstantiation;
import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.ChoiceRenderer;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.image.Image;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.StringResourceModel;
import org.apache.wicket.request.target.basic.RedirectRequestTarget;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.util.string.StringValue;

import brix.BrixNodeModel;
import brix.web.nodepage.BrixNodeWebPage;
import brix.web.nodepage.BrixPageParameters;

import com.googlecode.chigs.domain.ConfigRevision;
import com.googlecode.chigs.domain.Configuration;
import com.googlecode.chigs.domain.Product;
import com.googlecode.chigs.domain.UserSettings;
import com.googlecode.chigs.repository.ChigsFacade;
import com.googlecode.chigs.repository.ConfigurationStructureCreationException;
import com.googlecode.chigs.web.ChigsApplication;
import com.googlecode.chigs.web.ChigsWebSession;
import com.googlecode.chigs.web.config.configrevision.EditOrCreateConfigRevisionWizard;
import com.googlecode.chigs.web.config.configrevision.UpdateConfigRevisionWizard;
import com.googlecode.chigscommons.repository.GenericDomainService;
import com.googlecode.chigscommons.repository.MessageException;
import com.googlecode.chigscommons.web.WicketWebSession;
import com.googlecode.chigscommons.web.common.ActionPanelBuilder;
import com.googlecode.chigscommons.web.common.DeleteActionLink;
import com.googlecode.chigscommons.web.common.EditActionLink;
import com.googlecode.chigscommons.web.common.HistoryActionLink;
import com.googlecode.chigscommons.web.common.IconFactory;
import com.googlecode.chigscommons.web.common.UpdateActionLink;
import com.googlecode.chigscommons.web.common.ZipDownloadActionLink;
import com.googlecode.chigscommons.web.common.table.AjaxFallbackDefaultDataTableBuilder;
import com.googlecode.chigscommons.web.common.table.DefaultDataProvider;

/**
 * 
 * @author Ingo Renner
 * @author Henning Teek
 *
 */
@AuthorizeInstantiation("ROLE_USER")
public class ManageConfigurationsPanel extends Panel {
	@SpringBean
	private ChigsFacade chigs;

	@SpringBean
	private GenericDomainService genericDomainService;

	private final Link<Void> createLink;
    private Product product;

	private final UserSettings userSettings;
	
	public ManageConfigurationsPanel(String id, Long productId) {
		super(id);

		if (productId == null) {
			StringValue param = BrixPageParameters.getCurrent().getQueryParam("product");
			productId = !param.isEmpty() ? param.toLongObject() : null;
		}

		this.userSettings = ((ChigsWebSession) ChigsWebSession.get()).getUserSettings();
		this.product = productId != null ? genericDomainService.load(Product.class, productId) : userSettings.getProduct();
		
		add(getProductSelector());
		
		createLink = new Link<Void>("create") {
			@Override
			public void onClick() {
				EditOrCreateConfigRevisionWizard edit = new EditOrCreateConfigRevisionWizard(ManageConfigurationsPanel.this.getId(), product);
				edit.setOutputMarkupId(true);
				getPage().addOrReplace(edit);
				this.setVisible(false);
			}
		};
		createLink.add(new Image("icon", IconFactory.createAddGearIconReference()));
		createLink.setVisible(this.product != null);
		add(createLink);
		add(getComponentTable());
	}

	private DropDownChoice<Product> getProductSelector() {
		List<Product> products = genericDomainService.loadAll(Product.class);
		if (products.size() == 1){ // Selection nicht nötig
			ManageConfigurationsPanel.this.product = products.get(0);
		}
		return new DropDownChoice<Product>("product", new PropertyModel<Product>(this, "product"), products, new ChoiceRenderer<Product>("name", "id")){
			@Override
			protected void onSelectionChanged(Product product) {
				ManageConfigurationsPanel.this.product = product;
				userSettings.setProduct(product);
				genericDomainService.save(UserSettings.class, userSettings);
				getCreateLink().setVisible(true);
				ManageConfigurationsPanel.this.addOrReplace(getComponentTable());
			}
			@Override
			protected boolean wantOnSelectionChangedNotifications() {
				return true;
			}
		};
	}

	private Component getComponentTable() {
		final String id = "table";
		if (product == null || product.isNew()) {
			return new Label(id, "").setVisible(false);
		}
		return AjaxFallbackDefaultDataTableBuilder.getBuilder(ManageConfigurationsPanel.this)
		.addDataProvider(new DefaultDataProvider<Configuration>(new Configuration()))
		.add(new AbstractColumn<Object>(new StringResourceModel("actions.label", ManageConfigurationsPanel.this, null)) {
			@Override
			public void populateItem(Item cellItem, String componentId, IModel rowModel) {
				final ActionPanelBuilder linkBuilder = ActionPanelBuilder.getBuilder();
				final Configuration configuration = (Configuration) rowModel.getObject();
				// Eintrag editieren
				linkBuilder.add(new EditActionLink(false) {
					@Override
					public void onClick(AjaxRequestTarget target) {
						EditOrCreateConfigRevisionWizard edit = new EditOrCreateConfigRevisionWizard(ManageConfigurationsPanel.this.getId(), configuration, product);
						edit.setOutputMarkupId(true);
						ManageConfigurationsPanel.this.getParent().addOrReplace(edit);
					}
				});
				linkBuilder.add(new UpdateActionLink(false) {
					@Override
					public void onClick(AjaxRequestTarget target) {
						UpdateConfigRevisionWizard update = new UpdateConfigRevisionWizard(ManageConfigurationsPanel.this.getId(), configuration, product);
						update.setOutputMarkupId(true);
						ManageConfigurationsPanel.this.getParent().addOrReplace(update);
					}
				});
				final long configRevisionId = configuration.getLatestConfigRevision().getId().longValue();
				final ZipDownloadActionLink link = new ZipDownloadActionLink("config.zip"){
					@Override
					public File getFile() throws MessageException {
						try {
							ConfigRevision latestConfigRevision = genericDomainService.load(ConfigRevision.class, configRevisionId);
							return chigs.generateConfigurationFilestructure(latestConfigRevision);
						} catch (ConfigurationStructureCreationException e) {
							throw new MessageException(e.getMessage(),e);
						}
					}};
					linkBuilder.add(link);
				linkBuilder.add(new HistoryActionLink(false) {
					@Override
					public void onClick(AjaxRequestTarget target) {
						BrixPageParameters params = new BrixPageParameters();
						params.addQueryParam("product", product.getId().toString());
						params.addQueryParam("configuration", configuration.getId().toString());
						BrixNodeModel model = ((ChigsApplication) getApplication()).getI18nBrixLink(getSession(), "/configuration/revisions.html");
						getRequestCycle().setRequestTarget(new RedirectRequestTarget(params.urlFor(new BrixNodeWebPage(model))));
					}
				});
				// Delete darf nur ein Admin
				if (!((WicketWebSession) getSession()).getUser().isAdmin()) {
					DeleteActionLink removeLink = new DeleteActionLink(new StringResourceModel("actions.delete.confirm", ManageConfigurationsPanel.this, null), false) {
						@Override
						public void onClick(AjaxRequestTarget target) {
							genericDomainService.delete(Configuration.class, configuration);
						}
					};
					linkBuilder.add(removeLink);
				}
				cellItem.add(linkBuilder.build(componentId));
			}
		})				
		.addPropertyColumn("id", true)
		.addPropertyColumn("name", true)
		.addPropertyColumn("latestConfigRevision.nr", false)
		.addPropertyColumn("latestConfigRevision.version.version", false)
		.addPropertyColumn("latestConfigRevision.user.email", true)
		.setNumberOfRows(10)
		.build(id);
	}

	public Link<Void> getCreateLink() {
		return createLink;
	}

}
